package com.tang.mybatis.executor.statment;

import com.tang.mybatis.mapping.MappedStatement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tang
 * @classname SimpleStatementHandler
 * @description [  ]
 * @date 2022/4/8 22:13
 */
public class SimpleStatementHandler implements StatementHandler {

    private MappedStatement mappedStatement;

    private static Pattern param_pattern = Pattern.compile("#\\{([^\\{\\}]*)\\}");

    public SimpleStatementHandler(MappedStatement mappedStatement) {
        this.mappedStatement = mappedStatement;
    }

    @Override
    public PreparedStatement prepare(Connection connection) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(parseSymbol(mappedStatement.getSql()));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return preparedStatement;
    }

    @Override
    public ResultSet query(PreparedStatement preparedStatement) throws SQLException {
        return preparedStatement.executeQuery();
    }

    private static String parseSymbol(String source) {
        source = source.trim();
        Matcher matcher = param_pattern.matcher(source);
        return matcher.replaceAll("?");
    }
}